<template>
  <div :class="className" :style="{height:height,width:width}" ref="chartDiv"/>
</template>

<script>
  import * as echarts from 'echarts'

  require('echarts-wordcloud')
  import {debounce} from '@/utils'
  require('echarts/theme/royal') // echarts theme
  import html2canvas from "html2canvas";

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      optionTitleText: {
        type: String,
        default: ''
      },
      height: {
        type: String,
        default: '300px'
      },
      hots: {
        type: Array,
        default: []
      },
      saveImage: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        count:0,
        base64Image: undefined,
        chart: null,
        opinion: {
          title: {
            text: this.optionTitleText,
            padding: 10,
          },
          backgroundColor: '#fff',
          tooltip: {
            show: false
          },
          series: [{
            type: 'wordCloud',
            gridSize: 1,
            sizeRange: [12, 55],
            rotationRange: [-45, 0, 45, 90],
            textStyle: {
              normal: {
                color: function () {
                  return 'rgb(' +
                    Math.round(Math.random() * 255) +
                    ', ' + Math.round(Math.random() * 255) +
                    ', ' + Math.round(Math.random() * 255) + ')'
                }
              }
            },
            left: 'center',
            top: 'center',
            right: null,
            bottom: null,
            data: this.hots
          }]
        }
      }
    },
    mounted() {
      this.initChart()
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHandler)
      this.chart.dispose()
      this.chart = null
    },
    watch: {
      hots(newValue, oldValue) {
        this.opinion.series[0].data = newValue
        this.chart.setOption(this.opinion);
      },
      optionTitleText(newValue, oldValue) {
        this.opinion.title.text = newValue
        this.chart.setOption(this.opinion);
      },
    },
    methods: {
      doSaveImage() {
        let element = this.$refs.chartDiv
        const p1 = new Promise((resolve, reject) => {
          html2canvas(element).then(canvas => {
            this.base64Image = canvas.toDataURL("image/png")
            this.$emit("getBase64Image", this.base64Image)
            resolve()
          }).catch(error => {
            reject(error)
          });
        })
        const p = Promise.all([p1]);
        p.then(res => {
        })

      },
      initChart() {
        //定义一个promise对象 在内部执行我们的表格渲染代码
        let promise = new Promise((resolve, reject) => {
          this.chart = echarts.init(this.$el, 'royal')
          //option:图表的配置项和数据
          //notMerge:可选，是否不跟之前设置的option进行合并，默认为false，即合并。（这里是导致二次渲染不成功的根本）
          //lazyUpdate:可选，在设置完option后是否不立即更新图表，默认为false，即立即更新。
          this.chart.setOption(this.opinion, true, true)
          this.chart.on('click', param => {
            this.$emit('clickEvent', param.name)
          })
          // 绑定渲染停止时触发promise完成状态
          this.chart.on('finished', () => {
            this.count+=1
            if(this.count===3){
              resolve();
            }
          })
          this.__resizeHandler = debounce(() => {
            if (this.chart) {
              this.chart.resize()
            }
          }, 100)
          window.addEventListener('resize', this.__resizeHandler)
        });
        // 渲染完成后执行then()方法的操作代码
        promise.then(() => {
          if (this.saveImage) {
            console.log("开始保存图片")
            this.doSaveImage();
          }
        });
      }
    }
  }
</script>
